package com.hyy.book2.intercepter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyy.book2.constants.Constants;
import com.hyy.book2.model.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.net.http.HttpResponse;


@Slf4j
@Component
public class LoginIntercepter implements HandlerInterceptor {


    @Autowired//用来转换对象和json的
    private ObjectMapper objectMapper;


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        log.info("如果用户没有登陆将会被拦截....");
        HttpSession session = request.getSession(false);
        if (session == null
                || session.getAttribute(Constants.SESSION_USER_YEY) == null
                || !StringUtils.hasLength((String) session.getAttribute(Constants.SESSION_USER_YEY))) {
            log.error("用户未登录，已经拦截...");

            //设置状态码，无权限
            response.setStatus(HttpStatus.UNAUTHORIZED.value());

            Result result = Result.unlogin();

            //设置相应类型为json
            response.setContentType("application/json;charset=utf-8");

            //把result对象以字符串形式写入字节流中，最终也是对象，因为已经设置了相应个是为json
            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes("UTF-8"));
            response.getOutputStream().flush();
            return false;
        }
        return true;
    }


}
